package net.wanho.controller;

import lombok.RequiredArgsConstructor;
import net.wanho.constant.CommonConstant;
import net.wanho.dto.OutStoreDTO;
import net.wanho.po.OutStore;
import net.wanho.po.Product;
import net.wanho.service.OutStoreService;
import net.wanho.service.ProductService;
import net.wanho.service.StoreService;
import net.wanho.util.CurrentUtil;
import net.wanho.vo.OutStoreVo;
import net.wanho.vo.PageInfo;
import net.wanho.vo.R;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@RequestMapping("/outstore")
public class OutStoreController {
    private final StoreService storeService;
    private final OutStoreService outStoreService;
    private final ProductService productService;
    @GetMapping("/outstore-page-list")
    public R outStorePageList(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "5") Integer pageSize, OutStoreDTO outStoreDTO){
        PageInfo<OutStoreVo> pageInfo = outStoreService.outStorePageList(pageNum,pageSize,outStoreDTO);
        return R.success(pageInfo);
    }

    @GetMapping("/store-list")
    public R outStoreList(){
        return R.success(storeService.list());
    }

    @PutMapping("/outstore-confirm")
    public R outStoreConfirm(@RequestBody OutStore outStore){
        outStore.setTallyId(CurrentUtil.getUserId());
        outStore.setIsOut(CommonConstant.IS_OUT);

        /**
         * 减库存
         */
        Product product=new Product();
        product=productService.getById(outStore.getProductId());
        product.setProductInvent(product.getProductInvent()-outStore.getOutNum());
        if(product.getProductInvent()<outStore.getOutNum()){
            throw new RuntimeException("库存不足");
        }
        productService.updateById(product);

        outStoreService.updateById(outStore);
        return R.success("确认出库");
    }

    @GetMapping("/exportTable")
    public R exportTable(@RequestParam(defaultValue = "1") Integer pageNum,
                         @RequestParam(defaultValue = "5") Integer pageSize,
                         OutStoreDTO outStoreDTO){
        PageInfo<OutStoreVo> pageInfo = outStoreService.outStorePageList(pageNum,pageSize,outStoreDTO);
        return R.success(pageInfo.getResultList());
    }
    @PostMapping("/outstore-add")
    public R addOutStore(@RequestBody OutStore outStore){
        outStore.setIsOut(CommonConstant.IS_NOT_OUT);
        outStore.setOutPrice(outStore.getSalePrice());
        outStoreService.save(outStore);
        return R.success("添加成功");
    }
}
